#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_nettle_nettle_func_005.py
@Time:      2024/04/08 14:51:50
@Author:    zhixin
@Version:   1.0
@Contact:   zx01468051@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    zhixin
"""

from common.basetest import LocalTest
import re

class Test(LocalTest):
    """
    See tc_nettle_nettle_func_005.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """
    PARAM_DIC = {"pkg_name": "nettle nettle-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > nettle_test5.c <<EOF
#include <stdio.h>
#include <string.h>
#include <nettle/aes.h>

int main() {
    // AES-128的已知测试向量
    // 密钥 (16字节)
    const uint8_t key[16] = {
        0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
        0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c
    };
    // 明文 (16字节)
    const uint8_t plaintext[16] = {
        0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96,
        0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a
    };
    // 预期得到的密文 (16字节)
    const uint8_t expected_ciphertext[16] = {
        0x3a, 0xd7, 0x7b, 0xb4, 0x0d, 0x7a, 0x36, 0x60,
        0xa8, 0x9e, 0xca, 0xf3, 0x24, 0x66, 0xef, 0x97
    };
    uint8_t ciphertext[16];

    // AES环境初始化
    struct aes128_ctx ctx;
    aes128_set_encrypt_key(&ctx, key);

    // 加密明文
    aes128_encrypt(&ctx, sizeof(plaintext), ciphertext, plaintext);

    // 打印加密结果
    printf("加密结果：\\n");
    for (size_t i = 0; i < sizeof(ciphertext); ++i) {
        printf("%02x ", ciphertext[i]);
    }
    printf("\\n");

    // 比较实际的密文和预期的密文
    if (memcmp(expected_ciphertext, ciphertext, sizeof(ciphertext)) == 0) {
        printf("加密验证成功！加密输出与测试向量匹配。\\n");
    } else {
        printf("加密验证失败！加密输出与测试向量不匹配。\\n");
    }

    // 清理ctx
    memset(&ctx, 0, sizeof(ctx));

    return 0;
}
EOF"""

        self.cmd(cmdline)
    
    def test(self):
        self.cmd('gcc -o nettle_test5 nettle_test5.c -lnettle')
        code, nettle_result = self.cmd("./nettle_test5")
        self.assertIn('加密验证成功！加密输出与测试向量匹配。', nettle_result)


    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd('rm -rf nettle_test5 nettle_test5.c')
